package com.hongxun.design.utils.httputil;

import android.app.Activity;
import android.os.Handler;
import android.os.Message;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.hongxun.design.MyApp;
import com.hongxun.design.activitys.BaseActivity;
import com.hongxun.design.mytools.MString;
import com.hongxun.design.mytools.MyLog;
import com.hongxun.design.mytools.ShardPreferencesTool;
import com.hongxun.design.mytools.ToastShow;
import com.hongxun.design.ui.dialogstyle.MyDialog;
import com.hongxun.design.utils.fileutil.SetFileUtil;
import com.hongxun.design.utils.fileutil.ZipUtil;
import com.hongxun.design.utils.projectdatautil.DataFactory;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;

import java.io.File;
import java.io.IOException;

import static com.hongxun.design.MyApp.activity;


/**
 * Created by zerdoor_pc on 2015/10/12.
 */
public class HttpRootUtil {
    private static HttpUtils http;
    static HttpRootUtil instence;
    public boolean isLoad = true;

    public static HttpRootUtil getInsence() {
        if (instence == null) {
            instence = new HttpRootUtil();
        }
        if (http == null) {
            http = new HttpUtils();
        }
        return instence;
    }

    /**
     * get请求*
     */

//    class GetThread extends
    public void Get(String url, final Handler hander, final int i, final String... save) {

//        if (MyApp.NetWorkConnect) {
        if (!url.contains("?")) {
            url = url + "?openIdent=" + MyApp.openIdent;
        } else if (url.contains("?") && url.contains("=")) {
            url = url + "&openIdent=" + MyApp.openIdent;
        }
        //new
        String opou = ShardPreferencesTool.read(MyApp.activity, "opou", "", 1);
        url = url + "&openIdentuser=" + opou;

        setHttp();
        MyLog.L(MString.URL + url);
        http.send(HttpRequest.HttpMethod.GET, url, new RequestCallBack<String>() {
            @Override
            public void onStart() {
                if (isLoad && !(i == HttpStringUtil.SUCCESSED2 || i == HttpStringUtil.SUCCESSED3)) {
                    Loading(activity);
                }
            }

            @Override
            public void onLoading(long total, long current, boolean isUploading) {

            }

            @Override
            public void onSuccess(final ResponseInfo<String> responseInfo) {
                successed(hander, i, responseInfo, save);
                isLoad = true;
            }


            @Override
            public void onFailure(HttpException error, String msg) {
                Failure(hander, error, msg, i);
                isLoad = true;

            }
        });
//        } else {
//            Failure(hander, null, MString.Connection);
//        }


    }

    public void GetNo(String url, final Handler hander, final int i, final String... save) {

        http.configCurrentHttpCacheExpiry(0);
        http.configSoTimeout(20000);
        MyLog.L(MString.URL + url);
        http.send(HttpRequest.HttpMethod.GET, url, new RequestCallBack<String>() {
            @Override
            public void onStart() {

            }

            @Override
            public void onLoading(long total, long current, boolean isUploading) {

            }

            @Override
            public void onSuccess(final ResponseInfo<String> responseInfo) {
                successed(hander, i, responseInfo, save);
                isLoad = true;
            }


            @Override
            public void onFailure(HttpException error, String msg) {
                Failure(hander, error, msg, i);
                isLoad = true;

            }
        });
//        } else {
//            Failure(hander, null, MString.Connection);
//        }


    }

    /**
     * Post请求*
     */
    public void Post(String url, RequestParams params, final Handler hander, final int i, final String... save) {
//        if (MyApp.NetWorkConnect) {
        setHttp();
        if (MyApp.openIdent.length() > 0) {
            params.addBodyParameter("openIdent", MyApp.openIdent);
            //new
            String opou = ShardPreferencesTool.read(MyApp.activity, "opou", "", 1);
            params.addBodyParameter("openIdentuser", opou);
        }
        MyLog.L(MString.URL + url);

        http.send(HttpRequest.HttpMethod.POST, url, params, new RequestCallBack<String>() {
            @Override
            public void onStart() {
                if (isLoad) {
                    Loading(activity);
                }
            }

            @Override
            public void onLoading(long total, long current, boolean isUploading) {

            }

            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                successed(hander, i, responseInfo, save);
                isLoad = true;
            }

            @Override
            public void onFailure(HttpException error, String msg) {
                Failure(hander, error, msg, i);
                isLoad = true;
            }
        });
//        } else {
//            Failure(hander, null, MString.Connection);
//        }
    }


    /**
     * 下载请求*
     */
    public static boolean dowloadFlag = true;

    public void download(String path, final String newPath, final String name, String end, final Handler... uphandler) {
        File file = new File(newPath + name);
        if (file.exists()) {
            MyApp.File.delete(file);
        }
        File file1 = new File(newPath + name + end);
        if (file1.exists()) {
            MyApp.File.delete(file1);
        }
        http.configCurrentHttpCacheExpiry(0);
        http.configSoTimeout(60000);
        http.download(path, newPath + name + end, true, true, new RequestCallBack<File>() {
            @Override
            public void onStart() {
                MyLog.L(MString.SUCCESSED + "正在连接");
            }

            @Override
            public void onLoading(long total, long current, boolean isUploading) {
                MyLog.L(MString.SUCCESSED + current + "/" + total);
                BaseActivity.hideWaitIngDialog();
            }

            @Override
            public void onFailure(HttpException error, String msg) {
                MyLog.L(MString.SUCCESSED + " error:" + error);
                MyLog.L(MString.SUCCESSED + msg);
                if (uphandler != null && uphandler.length > 0 && uphandler[0] != null) {
                    uphandler[0].sendEmptyMessage(4);
                }
                if (dowloadFlag) {
                    ToastShow.showShort(activity, "下载失败！");
                } else {
                    ToastShow.showShort(activity, "拉取数据失败！");
                    if (uphandler != null && uphandler.length > 0 && uphandler[0] != null) {
                        uphandler[0].sendEmptyMessage(1);
                    }
                }
                BaseActivity.hideWaitIngDialog();
                dowloadFlag = true;
            }

            @Override
            public void onSuccess(ResponseInfo<File> responseInfo) {
                File file = responseInfo.result;
                // MyApp.File.copyFile(file, newPath + name);
                try {
                    String p1 = MyApp.File.getCachaPath() + MString.Project_ + SetFileUtil.CheckStageId_type();
                    MyApp.File.copyFolderPhotos(p1, MyApp.File.getCachaPath() + MString.Photos);
                    MyApp.File.delect(p1);//删除缓存文件夹

                    ZipUtil.upZipFile(file.getPath(), newPath, true);
                    MyApp.File.copyFolderPhotos(MyApp.File.getCachaPath() + MString.Photos, newPath + name, name);
                    MyApp.File.delect(MyApp.File.getCachaPath() + MString.Photos);
                    if (uphandler != null && uphandler.length > 0 && uphandler[0] != null) {
                        uphandler[0].sendEmptyMessage(1);
                    }
                    if (dowloadFlag) {
                        ToastShow.showShort(activity, "下载成功！");
                    }
                } catch (IOException e) {
                    MyLog.L(MString.SUCCESSED + "e:" + e.getMessage());
                }
                BaseActivity.hideWaitIngDialog();
                dowloadFlag = true;
                DataFactory.setUpdateOn(false);
                MyLog.L(MString.SUCCESSED + "downloaded:" + responseInfo.result.getPath());
            }
        });

    }


    public void download(String path, final String newPath, final Handler... uphandler) {

        http.configCurrentHttpCacheExpiry(0);
        http.configSoTimeout(60000);
        http.download(path, newPath, true, true, new RequestCallBack<File>() {
            @Override
            public void onStart() {
                MyLog.L(MString.SUCCESSED + "正在连接");
            }

            @Override
            public void onLoading(long total, long current, boolean isUploading) {
                MyLog.L(MString.SUCCESSED + current + "/" + total);
            }

            @Override
            public void onFailure(HttpException error, String msg) {

                //   ToastShow.showShort(MyApp.activity, "下载失败！"+error+"\n"+msg);
                MyLog.L(MString.SUCCESSED + "downloaded:" + error + "\n" + msg);
                BaseActivity.hideWaitIngDialog();
            }

            @Override
            public void onSuccess(ResponseInfo<File> responseInfo) {
                File file = responseInfo.result;
                if (!file.getPath().equals(newPath)) {
                    MyApp.File.copyFile(file, newPath);
                }
                MyLog.L(MString.SUCCESSED + "downloaded:" + responseInfo.result.getPath());
                BaseActivity.hideWaitIngDialog();
            }
        });

    }


    private void successed(Handler handler, int i, ResponseInfo<String> responseInfo, String... save) {
        JSONObject object = JSON.parseObject(responseInfo.result);
        boolean l10003 = false;
        boolean notlogin = false;
        boolean zero = false;
        if (object.containsKey("code")) {
            String code = object.getString("code");
            l10003 = code.equals("L10003");
        }
        if (object.containsKey("msg")) {
            String msg = object.getString("msg");
            notlogin = msg.equals("未登录") || msg.contains("δ��¼");
        }
//        if (object.containsKey("openIdent")) {
//            String openIdent = object.getString("openIdent");
//            zero = TextUtils.isEmpty(openIdent);
//        }
        if (zero || l10003 || notlogin) {
            MyApp.handler.sendEmptyMessage(7);
        } else {
            try {
                Message msg = new Message();
                msg.what = i;
                msg.obj = responseInfo.result;
                handler.sendMessage(msg);
                MyLog.L(MString.SUCCESSED + responseInfo.result);
            } catch (Exception e) {
            }
            close();
        }

    }

    private void Failure(Handler handler, HttpException error, String S, int i) {
        try {
            if (!(i == HttpStringUtil.SUCCESSED2 || i == HttpStringUtil.SUCCESSED3)) {

                Message msg = new Message();
                msg.what = HttpStringUtil.ERROR;
                msg.obj = S;
                if (error != null) {
                    switch (error.getExceptionCode()) {
                        case 0:
                            msg.obj = MString.Connection;
                            if (MyApp.isOnLine && !MyApp.NetWorkConnect) {
                                ToastShow.showShort(MyApp.context, MString.Connection);
                            }
                            break;
                    }
                }
                handler.sendMessage(msg);
                // MyLog.L(MString.ERROR + error.getExceptionCode() + "::" + error.toString());
                MyLog.L(MString.ERROR + S);
                if (S.equals("timed out")) {
                    MyLog.L(MString.SUCCESSED + " timed out:" + JSON.toJSONString(error));
                }
            }


        } catch (Exception e) {
        }
        close();
    }

    private void Loading(Activity context) {
        MyDialog.Loading(context);
    }

    public void close() {
        MyDialog.Close();
    }


    private void setHttp() {
        http.configSoTimeout(10000);
        http.configCurrentHttpCacheExpiry(0);
        http.configDefaultHttpCacheExpiry(5000);
        http.configTimeout(10000);
        http.configSoTimeout(20000);
        http.configRequestRetryCount(3);
        http.configRequestThreadPoolSize(4);
    }
}
